#! /usr/bin/env python3

import argparse
import os

from oclintscripts import environment
from oclintscripts import path
from oclintscripts import process

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-clean', '--clean', action="store_true")
args = arg_parser.parse_args()

def clean_module():
    build_path = path.build.clang_build_dir
    path.rm_f(build_path)
    install_dir = path.build.clang_install_dir
    path.rm_f(install_dir)

def setup_prebuilt_binary():
    build_path = path.build.clang_build_dir
    install_path = path.build.clang_install_dir

    if environment.is_darwin():
        if environment.is_aarch64_or_arm64():
            binary_url = path.url.clang_prebuilt_binary_for_macos_arm64
        else:
            binary_url = path.url.clang_prebuilt_binary_for_macos
    else:
        if environment.is_aarch64_or_arm64():
            binary_url = path.url.clang_prebuilt_binary_for_ubuntu_lts_20_aarch64
        else:
            binary_url = path.url.clang_prebuilt_binary_for_ubuntu_lts_20

    current_dir = os.getcwd()
    path.mkdir_p(build_path)
    path.cd(build_path)
    process.call('curl -L -o prebuilt.tar.xz ' + binary_url)
    path.mkdir_p(install_path)
    process.call('tar xf prebuilt.tar.xz -C ' + install_path + ' --strip-components=1')
    path.cd(current_dir)

    if environment.is_darwin():
        llvm_exports_cmake_path = os.path.join(install_path, 'lib', 'cmake', 'llvm', 'LLVMExports.cmake')
        llvm_exports_cmake_file = open(llvm_exports_cmake_path, 'r')
        llvm_exports_cmake_lines = llvm_exports_cmake_file.readlines()
        llvm_exports_cmake_lines[59] = '  INTERFACE_LINK_LIBRARIES "m;ZLIB::ZLIB;/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/lib/libcurses.tbd;LLVMDemangle"'
        llvm_exports_cmake_file = open(llvm_exports_cmake_path, 'w')
        llvm_exports_cmake_file.writelines(llvm_exports_cmake_lines)
        llvm_exports_cmake_file.close()

if args.clean:
    clean_module()
setup_prebuilt_binary()
